

/**
 * 获取和设置localStorage存储
 **/

let local = {
    save(key, value) {
        localStorage.setItem(key, JSON.stringify(value))
    },
    fetch(key) {
        return JSON.parse(localStorage.getItem(key)) || ''
    },
    remo(key) {
        localStorage.removeItem(key)
    }
};

let userId = {
    userId() {
        if (localStorage.getItem('userinfo')) {
            return JSON.parse(localStorage.getItem('userinfo')).user_id || ''
        } else {
            return 0
        }
    }
}
//判断手机什么系统
let system = {
    systemFun(Android, ios) {
        let u = navigator.userAgent
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
        let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isAndroid) {
            //这个是安卓操作系统
            Android()
        }
        if (isIOS) {
            //这个是ios操作系统
            ios()
        }
    }
}

/**
 * @param {String} str 需要格式的字符串
 * @param {Number} frontLen 前面保留的位数
 * @param {Number} endLen 后面保留的位数
 * @example 18788887353 => 187****7353
 * @returns {string} 格式化后的字符串
 */

function formaterWithMask(str, frontLen, endLen) {
    if (!str) return '';
    const len = str.length - frontLen - endLen;
    let xing = '';
    for (let i = 0; i < len; i++) {
        xing += '*';
    }
    return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
}


//时间格式转换
function getDateDiff(dateTime) {
    let dateTimeStamp = dateTime
    let result = '';
    let minute = 1000 * 60;
    let hour = minute * 60;
    let day = hour * 24;
    let halfamonth = day * 15;
    let month = day * 30;
    let year = day * 365;
    let now = new Date().getTime();
    let diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
        result = "刚刚"
        return result;
    }
    let monthEnd = diffValue / month;
    let weekEnd = diffValue / (7 * day);
    let dayEnd = diffValue / day;
    let hourEnd = diffValue / hour;
    let minEnd = diffValue / minute;
    let yearEnd = diffValue / year;
    if (yearEnd >= 1) {
        result = dateTime;
    } else if (monthEnd >= 1) {
        result = "" + parseInt(monthEnd) + "月前";
    } else if (weekEnd >= 1) {
        result = "" + parseInt(weekEnd) + "周前";
    } else if (dayEnd >= 1) {
        result = "" + parseInt(dayEnd) + "天前";
    } else if (hourEnd >= 1) {
        result = "" + parseInt(hourEnd) + "小时前";
    } else {
        result = formatTimeTwo(new Date(dateTimeStamp), 'h:m:s');
    }
    return result;
}


//时间格式转换
function formatTimeTwo(number, format) {
    // number 为时间格式
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];
    var date = number;
    returnArr.push(date.getFullYear());
    returnArr.push(date.getMonth() + 1);
    returnArr.push(date.getDate());
    returnArr.push(date.getHours());
    returnArr.push(date.getMinutes());
    returnArr.push(date.getSeconds());
    for (let y = 1; y < returnArr.length; y++) {
        if (returnArr[y] < 10) {
            returnArr[y] = '0' + returnArr[y]
        }
    }
    for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
}

//获取当前时间
let time = {
    timer(s) {
        var date = s;
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var getHours = date.getHours();
        var getMinutes = date.getMinutes();
        var getSeconds = date.getSeconds();
        return [year, month, strDate].map(formatNumber).join('-') + ' ' + [getHours, getMinutes].map(formatNumber).join(':')
    },

}
// 不满10 补零
function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}
//获取上一个月 / 下一个月
function timeMo(id, time) {
    let date = new Date(time);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;

    if (id == -1) {
        if (month == 1) {
            month = 12;
            year = year -= 1
        } else {
            month -= 1
        }
    } else if (id == 1) {
        if (month == 12) {
            month = 1;
            year = year += 1
        } else {
            month += 1
        }
    }
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    return `${year}-${month}`
}

//判断是否是银行卡
let card = {
    card(card, res) {
        var reg =
            /^(998801|998802|622525|622526|435744|435745|483536|528020|526855|622156|622155|356869|531659|622157|627066|627067|627068|627069)\d{10}$/;
        if (!reg.test(card)) {
            msg('请输入正确的银行卡！');
            return false
        }
        res()
    }
}
// 获取当前时间 '2020-01-01'
function getToday() {
    let date = new Date();
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(formatNumber).join('-');

}

// 获取当天凌晨00:00 的时间戳
function getTime() {
    let date = new Date();
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let time = y + "/" + m + "/" + d + ' 00:00';
    return new Date(time).getTime();
}




// 正则验证
function test(str, type) {
    switch (type) {
        case 'phone': //手机号码
            return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
        case 'tel': //座机
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'card': //身份证
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
        case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
            return /^[a-zA-Z]\w{5,17}$/.test(str)
        case 'postal': //邮政编码
            return /[1-9]\d{5}(?!\d)/.test(str);
        case 'QQ': //QQ号
            return /^[1-9][0-9]{4,9}$/.test(str);
        case 'email': //邮箱
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'money': //金额(小数点2位)
            return /^\d*(?:\.\d{0,2})?$/.test(str);
        case 'URL': //网址
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
        case 'IP': //IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
        case 'date': //日期时间
            return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(
                str)
        case 'number': //数字
            return /^[0-9]$/.test(str);
        case 'english': //英文
            return /^[a-zA-Z]+$/.test(str);
        case 'chinese': //中文
            return /^[\\u4E00-\\u9FA5]+$/.test(str);
        case 'lower': //小写
            return /^[a-z]+$/.test(str);
        case 'upper': //大写
            return /^[A-Z]+$/.test(str);
        case 'HTML': //HTML标记
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
        default:
            return true;
    }
}

// 获取累计时间
const getDeltaTime = (date) =>{
    let time1 = new Date(date).getTime(),
    time2 = new Date().getTime();
    let data = {};
    data.d = parseInt((time2 - time1) / 1000 / 60 / 60 / 24)? parseInt((time2 - time1) / 1000 / 60 / 60 / 24) - 1: 0;
    data.h = parseInt((time2 - time1 - (data.d ? data.d + 1 : data.d) * 24 * 60 * 60 * 1000) /1000 /60 /60);
    data.m = parseInt((time2 - time1 -(data.d ? data.d + 1 : data.d) * 24 * 60 * 60 * 1000 - data.h * 60 * 60 * 1000) /1000 /60);
    data.s = parseInt(((time2 - time1) / 1000) % 60);
    return data;
}









export default {
    install: function (vm) {
        vm.prototype.$local = local,
        vm.prototype.$system = system,
        vm.prototype.$user = userId,
        vm.prototype.$time = time,
        vm.prototype.$times = formatTimeTwo,
        vm.prototype.$timeMo = timeMo,
        vm.prototype.$getDateDiff = getDateDiff,
        vm.prototype.$test = test,
        vm.prototype.$getTime = getTime,
        vm.prototype.$getToday = getToday,
        vm.prototype.$formatNumber = formatNumber,
        vm.prototype.$getDeltaTime = getDeltaTime
    },
}